import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:live_music/components/feedback/PageFeedBack.dart';
import 'package:live_music/components/index/momentCard.dart';
import 'package:live_music/components/index/videoCard.dart';
import 'package:live_music/components/square/image_swiper_card.dart';
import 'package:live_music/models/square_images_model.dart';
import 'package:live_music/services/squareService.dart';

class ImageNoteSquare extends StatefulWidget {
  ImageNoteSquare({Key key}) : super(key: key);

  @override
  _ImageNoteSquareState createState() => _ImageNoteSquareState();
}

class _ImageNoteSquareState extends State<ImageNoteSquare>
    with AutomaticKeepAliveClientMixin {
  // 下拉刷新控制器
  EasyRefreshController _easyRefreshController;
  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController _scrollController;

  Map<String, List<SquareImageModel>> _squareImagesList;
  // 列表数组模型

  int pageNo = 1;
  int pageSize = 20;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String errorMsg;

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
    getData();
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  getData({bool replace = true}) async {
    try {
      Map<String, dynamic> data = {"pageNo": pageNo, "pageSize": pageSize};
      Map<String, dynamic> result = await SquareService.querySquareImage(data);
      Map<String, dynamic> imagesList = result['body'];
      Map<String, List<SquareImageModel>> squareImageListModel =
          imagesList.map((key, value) {
        SquareImageListModel imagesListModel =
            SquareImageListModel.fromJson(value);
        return MapEntry(key, imagesListModel.list);
      });
      List keys = squareImageListModel.keys.toList();
      int dataLength = 0;
      for (int i = 0; i < squareImageListModel.length; i++) {
        dataLength = dataLength + squareImageListModel[keys[i]].length;
      }
      setState(() {
        pageNo++;
        hasMore = pageSize == dataLength;
        if (replace) {
          _squareImagesList = squareImageListModel;
        } else {
          _squareImagesList.addAll(squareImageListModel);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  // 刷新回调(null为不开启刷新)
  Future _onRefresh() async {
    setState(() {
      pageNo = 1;
    });
    await getData(replace: true);
    if (error) {
      setState(() => error = false);
    }
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await getData(replace: false);
    }
    // // 结束加载
    _easyRefreshController.finishLoad(success: true, noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
        firstRefresh: false,
        firstRefreshWidget: PageFeedBack(firstRefresh: true).build(),
        emptyWidget: PageFeedBack(
          loading: loading,
          error: error,
          empty: _squareImagesList.isEmpty,
          errorMsg: errorMsg,
          onErrorTap: () => _easyRefreshController.callRefresh(),
          onEmptyTap: () => _easyRefreshController.callRefresh(),
        ).build(),
        header: PhoenixHeader(),
        footer: ClassicalFooter(),
        controller: _easyRefreshController,
        enableControlFinishRefresh: false,
        enableControlFinishLoad: true,
        onRefresh: _onRefresh,
        onLoad: _squareImagesList.isEmpty ? null : _onLoad,
        child: ListView.builder(
            controller: _scrollController,
            itemCount: _squareImagesList.length,
            itemBuilder: (BuildContext context, int index) {
              List keys = _squareImagesList.keys.toList();
              String key = keys[index];
              return Container(
                  color: Colors.white,
                  child: ImageSwiperCard(
                      date: key.toString(),
                      squareImageListModel: _squareImagesList[key]));
            }));
  }

  @override
  bool get wantKeepAlive => true;
}
